package com.cola.custSpeechTranscription;

/**
 * @BelongsProject: custSpeechTranscription
 * @BelongsPackage: com.cola.custSpeechTranscription
 * @Author: jiangkang
 * @CreateTime: 2025-10-31  14:56
 * @Description: TODO
 * @Version: 1.0
 */
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;
import java.nio.charset.StandardCharsets;

public class AESEncryption {
    private static final String MODE = "CBC";
    private static final String PADDING = "PKCS5Padding";
    private static final String IV = "W2V1PHkRjAIRhell";
    private static final String SECRET_KEY = "W2V1PHkRjAIRhell";

    public static String encrypt(String plainText) {
        try {
            byte[] keyBytes = SECRET_KEY.getBytes(StandardCharsets.UTF_8);
            byte[] ivBytes = IV.getBytes(StandardCharsets.UTF_8);

            SecretKeySpec secretKeySpec = new SecretKeySpec(keyBytes, "AES");
            IvParameterSpec ivParameterSpec = new IvParameterSpec(ivBytes);

            Cipher cipher = Cipher.getInstance("AES/" + MODE + "/" + PADDING);
            cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivParameterSpec);

            byte[] encryptedBytes = cipher.doFinal(plainText.getBytes(StandardCharsets.UTF_8));

            // Java 8使用DatatypeConverter
            return DatatypeConverter.printHexBinary(encryptedBytes).toLowerCase();

        } catch (Exception e) {
            throw new RuntimeException("AES加密失败", e);
        }
    }

    public static String decrypt(String encryptedHex) {
        try {
            byte[] keyBytes = SECRET_KEY.getBytes(StandardCharsets.UTF_8);
            byte[] ivBytes = IV.getBytes(StandardCharsets.UTF_8);

            SecretKeySpec secretKeySpec = new SecretKeySpec(keyBytes, "AES");
            IvParameterSpec ivParameterSpec = new IvParameterSpec(ivBytes);

            Cipher cipher = Cipher.getInstance("AES/" + MODE + "/" + PADDING);
            cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, ivParameterSpec);

            // Java 8使用DatatypeConverter
            byte[] encryptedBytes = DatatypeConverter.parseHexBinary(encryptedHex);

            byte[] decryptedBytes = cipher.doFinal(encryptedBytes);

            return new String(decryptedBytes, StandardCharsets.UTF_8);

        } catch (Exception e) {
            throw new RuntimeException("AES解密失败", e);
        }
    }

    public static void main(String[] args) {
        String plainText = "15217686217";
        System.out.println("明文: " + plainText);

        String encryptedText = encrypt(plainText);
        System.out.println("密文: " + encryptedText);

        String expected = "327a6c789e7985c6f8f9b6fd960a6e52";
        System.out.println("期望密文: " + expected);
        System.out.println("加密结果匹配: " + expected.equals(encryptedText));

        String decrypt = decrypt("c015aad4f72bfcbbec85f67f52589b27");
        System.out.println("解密"+decrypt);
    }
}